#!/bin/bash

# 云法务系统后端启动脚本
# Author: CloudLegal Team
# Date: 2024-01-01

# 设置颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 项目配置
PROJECT_NAME="cloud-legal-backend"
JAR_NAME="cloud-legal-backend-1.0.0.jar"
MAIN_CLASS="com.cloudlegal.CloudLegalApplication"
JVM_OPTS="-Xms512m -Xmx1024m -XX:+UseG1GC"
PROFILES_ACTIVE="dev"
SERVER_PORT="8080"

# 日志配置
LOG_DIR="logs"
LOG_FILE="$LOG_DIR/application.log"
PID_FILE="$PROJECT_NAME.pid"

# 创建日志目录
if [ ! -d "$LOG_DIR" ]; then
    mkdir -p "$LOG_DIR"
fi

# 函数：打印带颜色的消息
print_message() {
    local color=$1
    local message=$2
    echo -e "${color}[$(date '+%Y-%m-%d %H:%M:%S')] $message${NC}"
}

# 函数：检查Java环境
check_java() {
    if [ -z "$JAVA_HOME" ]; then
        print_message $YELLOW "JAVA_HOME未设置，尝试使用系统Java..."
        JAVA_CMD="java"
    else
        JAVA_CMD="$JAVA_HOME/bin/java"
    fi
    
    if ! command -v $JAVA_CMD &> /dev/null; then
        print_message $RED "错误：未找到Java环境，请安装JDK 17或更高版本"
        exit 1
    fi
    
    # 检查Java版本
    JAVA_VERSION=$($JAVA_CMD -version 2>&1 | head -n 1 | cut -d'"' -f2 | cut -d'.' -f1)
    if [ "$JAVA_VERSION" -lt 17 ]; then
        print_message $RED "错误：Java版本过低，需要JDK 17或更高版本"
        exit 1
    fi
    
    print_message $GREEN "Java环境检查通过：$($JAVA_CMD -version 2>&1 | head -n 1)"
}

# 函数：检查端口是否被占用
check_port() {
    if lsof -Pi :$SERVER_PORT -sTCP:LISTEN -t >/dev/null ; then
        print_message $YELLOW "警告：端口 $SERVER_PORT 已被占用"
        read -p "是否继续启动？(y/n): " -n 1 -r
        echo
        if [[ ! $REPLY =~ ^[Yy]$ ]]; then
            print_message $BLUE "启动已取消"
            exit 0
        fi
    fi
}

# 函数：检查进程是否运行
is_running() {
    if [ -f "$PID_FILE" ]; then
        local pid=$(cat "$PID_FILE")
        if ps -p $pid > /dev/null 2>&1; then
            return 0
        else
            rm -f "$PID_FILE"
            return 1
        fi
    fi
    return 1
}

# 函数：启动应用
start_app() {
    print_message $BLUE "正在启动 $PROJECT_NAME..."
    
    # 检查是否已经运行
    if is_running; then
        print_message $YELLOW "$PROJECT_NAME 已经在运行中"
        return 1
    fi
    
    # 检查JAR文件是否存在
    if [ ! -f "target/$JAR_NAME" ]; then
        print_message $YELLOW "JAR文件不存在，正在编译..."
        mvn clean package -DskipTests
        if [ $? -ne 0 ]; then
            print_message $RED "编译失败"
            exit 1
        fi
    fi
    
    # 启动应用
    nohup $JAVA_CMD $JVM_OPTS \
        -Dspring.profiles.active=$PROFILES_ACTIVE \
        -Dserver.port=$SERVER_PORT \
        -jar target/$JAR_NAME \
        > "$LOG_FILE" 2>&1 &
    
    local pid=$!
    echo $pid > "$PID_FILE"
    
    # 等待启动
    print_message $BLUE "等待应用启动..."
    sleep 5
    
    # 检查是否启动成功
    if is_running; then
        print_message $GREEN "$PROJECT_NAME 启动成功！"
        print_message $GREEN "PID: $(cat $PID_FILE)"
        print_message $GREEN "端口: $SERVER_PORT"
        print_message $GREEN "接口文档: http://localhost:$SERVER_PORT/api/doc.html"
        print_message $GREEN "日志文件: $LOG_FILE"
    else
        print_message $RED "$PROJECT_NAME 启动失败，请检查日志文件：$LOG_FILE"
        exit 1
    fi
}

# 函数：停止应用
stop_app() {
    print_message $BLUE "正在停止 $PROJECT_NAME..."
    
    if ! is_running; then
        print_message $YELLOW "$PROJECT_NAME 未运行"
        return 1
    fi
    
    local pid=$(cat "$PID_FILE")
    kill $pid
    
    # 等待进程结束
    local count=0
    while ps -p $pid > /dev/null 2>&1; do
        sleep 1
        count=$((count + 1))
        if [ $count -gt 30 ]; then
            print_message $YELLOW "强制停止进程..."
            kill -9 $pid
            break
        fi
    done
    
    rm -f "$PID_FILE"
    print_message $GREEN "$PROJECT_NAME 已停止"
}

# 函数：重启应用
restart_app() {
    stop_app
    sleep 2
    start_app
}

# 函数：查看状态
status_app() {
    if is_running; then
        local pid=$(cat "$PID_FILE")
        print_message $GREEN "$PROJECT_NAME 正在运行 (PID: $pid)"
        print_message $GREEN "端口: $SERVER_PORT"
        print_message $GREEN "接口文档: http://localhost:$SERVER_PORT/api/doc.html"
    else
        print_message $YELLOW "$PROJECT_NAME 未运行"
    fi
}

# 函数：查看日志
show_log() {
    if [ -f "$LOG_FILE" ]; then
        tail -f "$LOG_FILE"
    else
        print_message $YELLOW "日志文件不存在：$LOG_FILE"
    fi
}

# 函数：显示帮助信息
show_help() {
    echo "用法: $0 {start|stop|restart|status|log|help}"
    echo ""
    echo "命令说明："
    echo "  start   - 启动应用"
    echo "  stop    - 停止应用"
    echo "  restart - 重启应用"
    echo "  status  - 查看运行状态"
    echo "  log     - 查看实时日志"
    echo "  help    - 显示帮助信息"
    echo ""
    echo "示例："
    echo "  $0 start    # 启动应用"
    echo "  $0 status   # 查看状态"
    echo "  $0 log      # 查看日志"
}

# 主函数
main() {
    # 检查参数
    if [ $# -eq 0 ]; then
        show_help
        exit 1
    fi
    
    # 检查Java环境
    check_java
    
    # 根据参数执行相应操作
    case "$1" in
        start)
            check_port
            start_app
            ;;
        stop)
            stop_app
            ;;
        restart)
            restart_app
            ;;
        status)
            status_app
            ;;
        log)
            show_log
            ;;
        help)
            show_help
            ;;
        *)
            print_message $RED "未知命令: $1"
            show_help
            exit 1
            ;;
    esac
}

# 执行主函数
main "$@"
